package org.liaohailong.helloworld.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: liaohailong
 * Time: 2021/4/26 17:09
 * Describe:
 */
public class LeetCode1 {
    public static void main(String[] args) {
                int[] arr = {3, 2, 4};
        int target = 6;
        int[] ints = twoSum(arr, target);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> cache = new HashMap<>();
        for (int i = 0; i < nums.length; i++)
            cache.put(nums[i], i);

        for (int i = 0; i < nums.length; i++) {
            int key = target - nums[i];
            Integer index = cache.get(key);
            if (index != null && i != index) {
                int[] res = new int[2];
                res[0] = i;
                res[1] = index;
                return res;
            }
        }

        return new int[]{0, 1};
    }

}
